#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

int fd, led_fd;

void handler(int signum)
{
	close(fd);	
	close(led_fd);
	exit(0);
	return ;
}


int main(int argc, char *argv[])
{
	char buf[10];
	
	int val;
	char status = 0;

	signal(SIGINT, handler);
	
	if(argc < 2 || argc > 3){
		printf("please input 2 or 3 args, like\n");
		printf("./dev_test <dev> [string]\n");
		return 0;
	}

	
	fd = open(argv[1], O_RDWR);  // O_NONBLOCK 表示非阻塞
	if(fd < 0){
		printf("file open failed\n");
		return 1;
	}

	led_fd = open("/dev/led", O_RDWR);
	if(led_fd < 0){
		printf("/dev/led open failed\n");
		return 1;
	}

	while(1){
		read(fd, &val, 4);
		printf("key = %d, val = %d\n", val >> 8, val & 0xff);
		if((val & 0xff) == 0){
			//如果status为int类型，这样也可以，因为是小端模式
//				status ^= (1 << 7);
			status ^= 1;
			write(led_fd, &status, 1);
		}
	}

	
	return 0;
}

